A Sample Implementation
Various concepts were
previously covered, including Data Contracts, Message Contracts,
Endpoint Address, Faults, Behaviors, Bindings, Metadata Exchange (MEX)
and others.
The following example
pulls together several of the individual elements, attributes and
classes to present a very simple but complete service implementation.
The Greeting service has two operations: Greet1 and Greet2. Greet1 accepts a name parameter and returns a string with “Hello” prefixed to the name. Greet2
accepts a data contract comprised of populated First Name and Last Name
fields and returns a string with “Hello” appended to the name.
Example 3.
using System; using System.ServiceModel; using System.Runtime.Serialization; namespace HelloService { [ServiceContract(Namespace = "HelloService", Name = "IGreet")] public interface IGreet { [OperationContract] string Greet1(string name); [OperationContract] string Greet2(NameContract nameContractValue); } public class Greet : IGreet { public string Greet1(string name) { return "Hello: " + name; } public string Greet2(NameContract nameContractValue) { return "Hello: " + nameContractValue.FirstName; } } [DataContract] public class NameContract { [DataMember] public string FirstName {get; set;} [DataMember] public string LastName {get; set;} } }
|
In order to host the service in IIS, we need to create an “.svc” file and reference the service using the ServiceHost directive as shown here:
Example 4.
<% @ServiceHost Language=C# Debug="true" Service="HelloService.Greet" CodeBehind="~/App_Code/Greet.cs" %>
|
Finally, we need to configure the service endpoint’s address, binding, and contract in the Web.Config file:
Example 5.
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.serviceModel> <services> <service name="HelloService.Greet" behaviorConfiguration="GreetTypeBehaviors"> <endpoint address="mex" binding="mexHttpBinding" contract="HelloService.IGreet" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="GreetTypeBehaviors" > <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration>
|
The httpGetEnabled=true behavior indicates a WSDL definition is published with the service. includeExceptionDetailInFaults=true configures the service to return unhandled exceptions as faults and includeExceptionDetailInFaults=false will raise the actual exception to the service consumer.